package com.xdclass.userapp.service.dubbo;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.xdclass.userapp.mapper.TUserMapper;
import com.xdclass.userapp.model.domain.TUser;
import com.xdclass.userserviceapi.service.UserService;
import com.xdclass.userserviceapi.vo.UserVO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author whg
 * @create 2023/7/13 15:04
 * @description：
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private TUserMapper userMapper;

    private LoadingCache<Integer,TUser> userCache = CacheBuilder.newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .refreshAfterWrite(5,TimeUnit.MINUTES)
            .build(new CacheLoader<Integer, TUser>() {
                @Override
                public TUser load(Integer integer) throws Exception {
                    return loadUser(integer);
                }
            });

    /**
     * 通过用户ID得到用户信息
     * @param id
     * @return
     */
    @Override
    public UserVO getUserById(Integer id) {
        TUser user = userCache.getUnchecked(id);
        if (null == user){
            return null;
        }else {
            UserVO vo = new UserVO();
            BeanUtils.copyProperties(user,vo);
            return vo;
        }
    }

    private TUser loadUser(Integer id){
        TUser user = userMapper.selectByPrimaryKey(id);
        return user;
    }
}
